//
//  JKShowPictureViewController.m
//  Baisi
//
//  Created by albert on 16/3/22.
//  Copyright (c) 2016年 albert. All rights reserved.
//

#import "JKShowPictureViewController.h"
#import "UIImageView+WebCache.h"
#import "JKPostModel.h"
#import "SVProgressHUD.h"
#import "JKProgressView.h"
#import "JKTopWindowViewController.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import <Photos/Photos.h>

typedef NS_ENUM(NSUInteger, JKPhotoPickerScrollDirection) {
    JKPhotoPickerScrollDirectionNone,
    JKPhotoPickerScrollDirectionUp,
    JKPhotoPickerScrollDirectionDown,
};

@interface JKShowPictureViewController () <UIScrollViewDelegate>
{
    BOOL isDragging;
    BOOL isGonnaDismiss;
    
    CGFloat bgAlpha;
    CGFloat lastOffsetY;
    CGFloat currentOffsetY;
    
    CGPoint willDismissOffset;
    
    JKPhotoPickerScrollDirection beginScrollDirection;
    JKPhotoPickerScrollDirection endScrollDirection;
}
@property (weak, nonatomic) IBOutlet UIView *containerView;

@property (weak, nonatomic) IBOutlet UIScrollView *scrollView;
@property (weak, nonatomic) IBOutlet UIButton *backButton;
@property (weak, nonatomic) IBOutlet UIButton *saveButton;

/** 图片imageView */
@property (nonatomic, weak) JKAnimatedImageView *pictureImageView;

/** 进度条 */
@property (weak, nonatomic) IBOutlet JKProgressView *progressView;

/** 是否正在缩放 */
@property (nonatomic, assign) BOOL isZooming;

/** 图片是否已加载成功 */
@property (nonatomic, assign) BOOL imageLoaded;
@end

@implementation JKShowPictureViewController

+ (void)showWithPost:(JKPostModel *)post touchPoint:(CGPoint)touchPoint sourceVc:(UIViewController *)sourceVc{
    
    JKShowPictureViewController *showPictureVc = [[JKShowPictureViewController alloc] init];
    
    //给控制器添加一个模型属性，将模型数据传给它
    showPictureVc.post = post;
    
    JKShowPicturePresentationManager.shared.touchPoint = touchPoint;
    showPictureVc.transitioningDelegate = JKShowPicturePresentationManager.shared;
    showPictureVc.modalPresentationStyle = UIModalPresentationCustom;
    
    if (sourceVc != nil && [sourceVc isKindOfClass:[UIViewController class]]) {
        
        [sourceVc presentViewController:showPictureVc animated:YES completion:nil];
        
        return;
    }
    
    [[UIApplication sharedApplication].delegate.window.rootViewController presentViewController:showPictureVc animated:YES completion:nil];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    UIView *statusBar = [[UIApplication sharedApplication] valueForKeyPath:@"statusBar"];
    
    [UIView animateWithDuration:0.5 animations:^{
        
        statusBar.alpha = 0;
        
    } completion:^(BOOL finished) {
        
    }];
}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    
    UIView *statusBar = [[UIApplication sharedApplication] valueForKeyPath:@"statusBar"];
    
    [UIView animateWithDuration:0.5 animations:^{
        
        statusBar.alpha = 1;
        
    } completion:^(BOOL finished) {
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 隐藏状态栏，有bug暂未解决
    //[JKTopWindowViewController sharedTopWindow].statusBarHidden = YES;
    
    //设置手势
    [self setupGestures];
    
    //设置图片显示
    [self setupImageShowing];
    
    //立刻显示最新的进度值（防止因为网速慢，导致显示的是其它cell图片的下载进度）
    [self.progressView setProgress:self.post.pictureProgress animated:NO];
    
    //设置图片
    [self setImage];
    
    //设置scrollView的代理
    self.scrollView.delegate = self;
    self.scrollView.alwaysBounceVertical = YES;
    self.scrollView.minimumZoomScale = 1;
    self.scrollView.maximumZoomScale = 2;
    
//    [UIApplication sharedApplication].statusBarHidden = YES;
}

// 设置手势
- (void)setupGestures{
    
    // 单击手势
    UITapGestureRecognizer *singleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(tap:)];
    [singleTap setNumberOfTapsRequired:1];
    // 添加单击手势
    [self.scrollView addGestureRecognizer:singleTap];
    
    // 双击手势
    UITapGestureRecognizer *doubleTap = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(doubleTap:)];
    [doubleTap setNumberOfTapsRequired:2];
    // 添加双击手势
    [self.scrollView addGestureRecognizer:doubleTap];
    
    //这行很关键，意思是只有当没有检测到doubleTapGestureRecognizer 或者 检测doubleTapGestureRecognizer失败，singleTapGestureRecognizer才有效
    [singleTap requireGestureRecognizerToFail:doubleTap];
    
    // 单击手势
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc]initWithTarget:self action:@selector(longPress:)];
    
    // 添加单击手势
    [self.scrollView addGestureRecognizer:longPress];
}

- (void)longPress:(UILongPressGestureRecognizer *)gesture{
    
    if (gesture.state == UIGestureRecognizerStateBegan) {
        
        [JKAlertView alertViewWithTitle:nil message:nil style:(JKAlertStyleActionSheet)].addAction([JKAlertAction actionWithTitle:@"保存到相册" style:(JKAlertActionStyleDefault) handler:^(JKAlertAction *action) {
            
            [self savePicture];
            
        }]).show();
    }
}

// 双击手势
- (void)doubleTap:(UITapGestureRecognizer *)tap{
    NSLog(@"双击之前%@", NSStringFromCGRect(self.pictureImageView.frame));
    NSLog(@"双击");
    
    CGPoint touchPoint = [tap locationInView:self.view];
    
    CGPoint point = [self.pictureImageView convertPoint:touchPoint fromView:self.view];
    
    if (![self.pictureImageView pointInside:point withEvent:nil]) {
        return;
    }
    
    // 双击缩小
    if (self.scrollView.zoomScale > 1) {
        [self.scrollView setZoomScale:1 animated:YES];
        return;
    }
    
    // 双击放大
    [self.scrollView zoomToRect:CGRectMake(point.x - 5, point.y - 5, 10, 10) animated:YES];
}

//设置图片显示
- (void)setupImageShowing {
    
    //创建imageView，不能在xib中拖，因为约束不好添加
    JKAnimatedImageView *pictureImageView = [[JKAnimatedImageView alloc] init];
//    pictureImageView.runLoopMode = NSRunLoopCommonModes;
    self.pictureImageView = pictureImageView;
    
    [self.scrollView addSubview:pictureImageView];
}

- (void)viewWillLayoutSubviews{
    [super viewWillLayoutSubviews];
}

- (void)calculateImageSize{
    
    //图片要显示的尺寸
    CGFloat pictureW = JKScreenW;
    CGFloat pictureH = JKScreenW * [self.post.height floatValue] / [self.post.width floatValue];
    
    self.scrollView.contentSize = CGSizeMake(pictureW, pictureH);
    
    if (pictureH > JKScreenH) {//图片高过屏幕
        
//        self.scrollView.contentSize = CGSizeMake(pictureW, pictureH);
        
        //        self.pictureImageView.frame = CGRectMake(0, 0, pictureW, pictureH);
        //设置scrollView的contentSize
        JKLog(@"更新了contentSize");
        
    }else{//图片不高于屏幕
        
        [self.scrollView jk_adapt_iOS_11_scrollView];
        //        self.pictureImageView.size = CGSizeMake(pictureW, pictureH);
        //图片显示在中间
        //        self.pictureImageView.centerY = self.view.height * 0.5;
        //        self.pictureImageView.centerX = self.view.width * 0.5;
    }
    
    self.pictureImageView.frame = CGRectMake(0, 0, pictureW, pictureH);
    
    [self setInset];
}

- (void)setImage{
    
    //图片显示
    [self.pictureImageView fl_setImageWithURL:[NSURL URLWithString:self.post.large_image] placeholderImage:nil options:0 progress:^(NSInteger receivedSize, NSInteger expectedSize, NSURL * _Nullable targetURL) {
        
        //进度，把 1.0 放在后面没有效果？？
        self.post.pictureProgress = 1.0 * receivedSize / expectedSize;
        
        dispatch_async(dispatch_get_main_queue(), ^{
            
            //显示进度条
            self.progressView.hidden = NO;
            
            //设置进度条
            [self.progressView setProgress:self.post.pictureProgress animated:NO];
        });
        
    } completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) {
        
        //完成后隐藏进度条
        self.progressView.hidden = YES;
        
        [self calculateImageSize];
        
        if (error == nil) {
            
            self.imageLoaded = YES;
        }
    }];
}

- (void)tap:(UITapGestureRecognizer *)tap {
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.4 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        
        self.containerView.alpha = 0;
    });
    
    CGPoint location = [tap locationInView:tap.view];
    
    location = [tap.view convertPoint:location toView:self.view];
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
    [JKShowPicturePresentationManager animationWithView:self.view duration:0.5 transitionContext:nil isPresent:NO touchPoint:location];
}

//保存图片
- (IBAction)savePicture {
    
    //没下载完时不允许保存
    if (!self.imageLoaded) {
        [JKProgressHUD showErrorWithStatus:@"图片尚未下载完毕！"];
        return;
    }
    
    [JKProgressHUD showWithStatus:@"正在保存图片..." isAllowUserAction:NO];
    
    //将图片保存到相册
    //    UIImageWriteToSavedPhotosAlbum(self.pictureImageView.image, self, @selector(image:didFinishSavingWithError:contextInfo:), nil);
    //
    //    [PHAssetChangeRequest creationRequestForAssetFromImage:self.pictureImageView.image];
    
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        
        NSString *cachePath = [[[SDWebImageManager sharedManager] imageCache] defaultCachePathForKey:self.post.large_image];
        
        NSURL *url = (cachePath ?
                      [NSURL fileURLWithPath:cachePath] :
                      [NSURL URLWithString:self.post.large_image]);
        
        [[[ALAssetsLibrary alloc] init] writeImageDataToSavedPhotosAlbum:[NSData dataWithContentsOfURL:url] metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {
            
            dispatch_async(dispatch_get_main_queue(), ^{
                
                if (error) {
                    
                    [JKProgressHUD showErrorWithStatus:@"保存图片失败！"];
                    
                }else{
                    
                    [JKProgressHUD showSuccessWithStatus:@"保存图片成功！"];
                }
            });
        }];
    });
}

// 保存到相册调用的方法必须传参数，否则会崩溃，下面的方法是系统建议的，可以自己写，但必须带参数
- (void)image:(UIImage *)image didFinishSavingWithError:(NSError *)error contextInfo:(void *)contextInfo{
    
    if (error) {
        
        [JKProgressHUD showErrorWithStatus:@"保存图片失败！"];
        
    }else{
        
        [JKProgressHUD showSuccessWithStatus:@"保存图片成功！"];
    }
}

- (IBAction)repostPicture {
    
}

#pragma mark - <UIScrollViewDelegate>
- (UIView *)viewForZoomingInScrollView:(UIScrollView *)scrollView{
    return self.pictureImageView;
}

- (void)scrollViewDidZoom:(UIScrollView *)scrollView{
    
    //    if (self.pictureImageView.height < self.view.height) {
    //        self.pictureImageView.centerY = self.view.centerY;
    //
    //    }else{
    //        self.pictureImageView.y = 0;
    //    }
    
    [self setInset];
}

- (void)setInset{
    // 计算内边距，注意只能使用frame
    CGFloat offsetX = (JKScreenW - self.pictureImageView.frame.size.width) * 0.5;
    CGFloat offsetY = (JKScreenH - self.pictureImageView.frame.size.height) * 0.5;
    
    // 当小于0的时候，放大的图片将无法滚动，因为内边距为负数时限制了它可以滚动的范围
    offsetX = (offsetX < 0) ? 0 : offsetX;
    offsetY = (offsetY < 0) ? 0 : offsetY;
    
    self.scrollView.contentInset = UIEdgeInsetsMake(offsetY, offsetX, offsetY, offsetX);//UIEdgeInsets(top: offsetY, left: offsetX, bottom: offsetY, right: offsetX)
}

- (void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    NSLog(@"contentSize == %@      contentOffset == %@", NSStringFromCGSize(scrollView.contentSize), NSStringFromCGPoint(scrollView.contentOffset));
    
    if (isDragging) {
        
        currentOffsetY = scrollView.contentOffset.y;
        
        if (currentOffsetY > lastOffsetY) {
            
            if (beginScrollDirection == JKPhotoPickerScrollDirectionNone) {
                
                beginScrollDirection = JKPhotoPickerScrollDirectionUp;
            }
            
            endScrollDirection = JKPhotoPickerScrollDirectionUp;
            
            //            JKLog("上滑-------")
        }
        
        if (currentOffsetY < lastOffsetY) {
            
            //            JKLog("下滑-------")
            
            if (beginScrollDirection == JKPhotoPickerScrollDirectionNone) {
                
                beginScrollDirection = JKPhotoPickerScrollDirectionDown;
            }
            
            endScrollDirection = JKPhotoPickerScrollDirectionDown;
        }
        
        lastOffsetY = currentOffsetY;
    }
    
    
    
    if (isGonnaDismiss || _isZooming) { return; }
    
    scrollView.pinchGestureRecognizer.enabled = (scrollView.contentOffset.y + scrollView.contentInset.top > -20 && (scrollView.contentOffset.y + scrollView.contentInset.top < 20));
    
    if (scrollView.contentOffset.y + scrollView.contentInset.top <= 1) { // 向下滑动
        
        bgAlpha = 1 - ((-scrollView.contentOffset.y - scrollView.contentInset.top) / off * 0.2);
        
        self.containerView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:bgAlpha];
        
        return;
    }
    
    // 向上滑动
    if (scrollView.contentSize.height + scrollView.contentInset.top + scrollView.contentInset.bottom <= scrollView.bounds.size.height) {
        
        bgAlpha = 1 - (scrollView.contentOffset.y + scrollView.contentInset.top) / off * 0.2;
    }
    
    if (scrollView.contentSize.height + scrollView.contentInset.top + scrollView.contentInset.bottom > scrollView.bounds.size.height) {
        
        bgAlpha = 1 - (scrollView.contentOffset.y + scrollView.bounds.size.height - scrollView.contentInset.bottom - scrollView.contentSize.height) / off * 0.2;
    }
    
    self.containerView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:bgAlpha];
}

static CGFloat off = 80;

- (void)scrollViewWillBeginZooming:(UIScrollView *)scrollView withView:(UIView *)view{
    self.isZooming = YES;
}

- (void)scrollViewDidEndZooming:(UIScrollView *)scrollView withView:(UIView *)view atScale:(CGFloat)scale{
    
    NSLog(@"endZoom");
    
    self.isZooming = NO;
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    
    isDragging = YES;
    
    beginScrollDirection = JKPhotoPickerScrollDirectionNone;
    endScrollDirection = JKPhotoPickerScrollDirectionNone;
    
    lastOffsetY = scrollView.contentOffset.y;
}

- (void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset{
    
    if (_isZooming || (beginScrollDirection != endScrollDirection)) { return; }
    
    if (scrollView.contentOffset.y + scrollView.contentInset.top < -off) {
        
        UIEdgeInsets inset = scrollView.contentInset;
        
        inset.top = -(scrollView.contentOffset.y);
        
        scrollView.contentInset = inset;
        
        [self stopScrolling:scrollView];
        
        [self dismissAnimation:scrollView isScrollToTop:NO];
    }
    
    if (scrollView.contentSize.height + scrollView.contentInset.top + scrollView.contentInset.bottom <= scrollView.bounds.size.height &&
        scrollView.contentOffset.y + scrollView.contentInset.top > off) {
        
        UIEdgeInsets inset = scrollView.contentInset;
        
        inset.bottom += scrollView.contentOffset.y + scrollView.contentInset.top;
        
        scrollView.contentInset = inset;
        
        [self stopScrolling:scrollView];
        
        [self dismissAnimation:scrollView isScrollToTop:YES];
    }
    
    if ((scrollView.contentSize.height + scrollView.contentInset.top + scrollView.contentInset.bottom > scrollView.bounds.size.height) &&
        (scrollView.contentOffset.y + scrollView.bounds.size.height - scrollView.contentInset.bottom - scrollView.contentSize.height > off)) {
        
        UIEdgeInsets inset = scrollView.contentInset;
        
        inset.bottom += (scrollView.contentOffset.y + scrollView.bounds.size.height - scrollView.contentInset.bottom - scrollView.contentSize.height);
        
        scrollView.contentInset = inset;
        
        [self stopScrolling:scrollView];
        
        [self dismissAnimation:scrollView isScrollToTop:YES];
    }
}
/** 停止scrollView滚动 */
- (void)stopScrolling:(UIScrollView *)scrollView{
    
    isGonnaDismiss = YES;
    scrollView.bounces = NO;
    scrollView.alwaysBounceVertical = NO;
    scrollView.decelerationRate = 0;
    
    willDismissOffset = scrollView.contentOffset;
    
    [scrollView setContentOffset:willDismissOffset animated:NO];//(willDismissOffset, animated: false)
}

/** dismissAnimation */
- (void)dismissAnimation:(UIScrollView *)scrollView isScrollToTop:(BOOL)isScrollToTop {
    
//    scrollView.contentOffset = willDismissOffset;

    CGRect rect = [scrollView convertRect:self.pictureImageView.frame toView:[UIApplication sharedApplication].delegate.window];

    self.pictureImageView.frame = rect;
    
    [self.view addSubview:self.pictureImageView];

    isScrollToTop ? (rect.origin.y -= JKScreenH) : (rect.origin.y += JKScreenH);
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
    [UIView animateWithDuration:0.5 animations:^{
        
        self.pictureImageView.frame = rect;
        self.containerView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
//        self.backButton.alpha = 0;
//        self.saveButton.alpha = 0;
        
    } completion:^(BOOL finished) {
        
    }];
    
    //        let offSetY = scrollView.contentOffset.y
    //
    //        scrollView.setContentOffset(CGPoint(x: scrollView.contentOffset.x, y: isScrollToTop ? offSetY + JKScreenH : offSetY - JKScreenH), animated: true)
}

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate{
    //    scrollView.userInteractionEnabled = YES;
    
    isDragging = NO;
    
    beginScrollDirection = JKPhotoPickerScrollDirectionNone;
    endScrollDirection = JKPhotoPickerScrollDirectionNone;
    
    scrollView.pinchGestureRecognizer.enabled = YES;
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    
    scrollView.pinchGestureRecognizer.enabled = YES;
}
@end


#pragma mark - 自定义动画


@interface JKShowPicturePresentationController : UIPresentationController
@end

@implementation JKShowPicturePresentationController

- (void)containerViewDidLayoutSubviews{
    [super containerViewDidLayoutSubviews];
    
    self.presentedView.frame = [UIScreen mainScreen].bounds;
    self.presentedView.userInteractionEnabled = YES;
}
@end


@interface JKShowPicturePresentationManager () <CAAnimationDelegate>

/** 是否已经被present */
@property (nonatomic, assign) BOOL isPresent;
@end

static JKShowPicturePresentationManager *shared_;

@implementation JKShowPicturePresentationManager

+ (JKShowPicturePresentationManager *)shared{
    
    if (shared_ == nil) {
        
        shared_ = [[JKShowPicturePresentationManager alloc] init];
    }
    
    return shared_;
}

#pragma mark - UIViewControllerTransitioningDelegate协议方法

- (UIPresentationController *)presentationControllerForPresentedViewController:(UIViewController *)presented presentingViewController:(UIViewController *)presenting sourceViewController:(UIViewController *)source{
    
    
    JKShowPicturePresentationController *vc = [[JKShowPicturePresentationController alloc] initWithPresentedViewController:presented presentingViewController:presenting];
    
    
    return vc;
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForPresentedController:(UIViewController *)presented presentingController:(UIViewController *)presenting sourceController:(UIViewController *)source{
    
    self.isPresent = YES;
    
    return self;
}

- (id<UIViewControllerAnimatedTransitioning>)animationControllerForDismissedController:(UIViewController *)dismissed{
    
    self.isPresent = NO;
    
    return self;
}

#pragma mark - UIViewControllerAnimatedTransitioning协议方法

- (NSTimeInterval)transitionDuration:(nullable id<UIViewControllerContextTransitioning>)transitionContext {
    return 0.5;
}

- (void)animateTransition:(nonnull id<UIViewControllerContextTransitioning>)transitionContext {
    
    if (self.isPresent) {// 展现
        
        [self willPresentController:transitionContext];
        
    }else {//消失
        
        [self willDismissController:transitionContext];
    }
}


#pragma mark - 执行展现的动画
- (void)willPresentController:(id<UIViewControllerContextTransitioning>)transitionContext{
    
    // 1.获取要弹出的视图
    // 通过ToViewKey取出来的就是toVc对应的view
    UIView *toView = [transitionContext viewForKey:UITransitionContextToViewKey];
    
    if (toView == nil) return;
    
//    toView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:1];
    
    // 2.将需要弹出的视图添加到containerView上
    [[transitionContext containerView] addSubview:toView];
//    [[transitionContext containerView] setBackgroundColor:[UIColor blackColor]];
    
    [JKShowPicturePresentationManager presentAnimationWithView:toView duration:[self transitionDuration:transitionContext] transitionContext:transitionContext];
}

#pragma mark - 执行消失的动画
- (void)willDismissController:(id<UIViewControllerContextTransitioning>)transitionContext{
    
    UIView *fromView = [transitionContext viewForKey:UITransitionContextFromViewKey];
    
    if (fromView == nil) return;
    
    [UIView animateWithDuration:[self transitionDuration:transitionContext] animations:^{
        
        fromView.backgroundColor = [[UIColor blackColor] colorWithAlphaComponent:0];
        
    } completion:^(BOOL finished) {
        
        [transitionContext completeTransition:YES];
    }];
}

#pragma mark - 封装为类方法

+ (void)presentAnimationWithView:(UIView *)animationView duration:(CGFloat)duration transitionContext:(id<UIViewControllerContextTransitioning>)transitionContext{
    
    [self animationWithView:animationView duration:duration transitionContext:transitionContext isPresent:YES touchPoint:JKShowPicturePresentationManager.shared.touchPoint];
}

+ (void)dismissAnimationWithView:(UIView *)animationView duration:(CGFloat)duration transitionContext:(id<UIViewControllerContextTransitioning>)transitionContext{
    
    [self animationWithView:animationView duration:duration transitionContext:transitionContext isPresent:NO touchPoint:CGPointZero];
}

+ (void)animationWithView:(UIView *)animationView duration:(CGFloat)duration transitionContext:(id<UIViewControllerContextTransitioning>)transitionContext isPresent:(BOOL)isPresent touchPoint:(CGPoint)touchPoint{
    
    // 画两个圆路径
    UIBezierPath *startCirclePath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(touchPoint.x == 0 ? JKScreenW * 0.5 : touchPoint.x, touchPoint.y == 0 ? JKScreenH * 0.5 : touchPoint.y, 0, 0)];
    
    CGFloat radius = sqrtf(JKScreenW * 0.5 * JKScreenW * 0.5 + JKScreenH * 0.5 * JKScreenH * 0.5);
    
    UIBezierPath *endCirclePath = [UIBezierPath bezierPathWithOvalInRect:CGRectMake(JKScreenW * 0.5 - radius, JKScreenH * 0.5 - radius, radius * 2, radius * 2)];
    
    // 创建CAShapeLayer进行遮盖
    CAShapeLayer *maskLayer = [[CAShapeLayer alloc] init];
    maskLayer.path = endCirclePath.CGPath;
    animationView.layer.mask = maskLayer;
    
    // 创建路径动画
    CABasicAnimation *maskLayerAnimation = [CABasicAnimation animationWithKeyPath:@"path"];
    maskLayerAnimation.delegate = JKShowPicturePresentationManager.shared;
    maskLayerAnimation.fromValue = isPresent ? (__bridge id _Nullable)(startCirclePath.CGPath) : (__bridge id _Nullable)(endCirclePath.CGPath);
    maskLayerAnimation.toValue = isPresent ? (__bridge id _Nullable)(endCirclePath.CGPath) : (__bridge id _Nullable)(startCirclePath.CGPath);
    maskLayerAnimation.duration = duration;//transitionDuration(using: transitionContext)
    maskLayerAnimation.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    
//    maskLayerAnimation.removedOnCompletion = NO;
//    maskLayerAnimation.fillMode = kCAFillModeForwards;
    
    if (transitionContext != nil) {
        
        [maskLayerAnimation setValue:transitionContext forKey:@"transitionContext"];
    }
    
    [maskLayer addAnimation:maskLayerAnimation forKey:@"path"];
}

#pragma mark - 核心动画代理

- (void)animationDidStop:(CAAnimation *)anim finished:(BOOL)flag{
    
    id<UIViewControllerContextTransitioning> transitionContext = [anim valueForKey:@"transitionContext"];
    
    if (transitionContext != nil) {
        
        [transitionContext completeTransition:YES];
    }
}
@end
